let socket = null;

export function connectWebSocket(userId, handlers) {
  const wsProtocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
  const socket = new WebSocket(`${wsProtocol}${window.location.host}/ws/chat/`);

  socket.onmessage = (e) => {
    const data = JSON.parse(e.data);
    switch(data.type) {
      case 'new_message':
        if (handlers.onNewMessage) handlers.onNewMessage(data.data);
        break;
      case 'read_receipt':
        if (handlers.onReadReceipt) handlers.onReadReceipt(data.message_id);
        break;
    }
  };

  return socket;
}

export function sendWebSocketMessage(message) {
  if (socket && socket.readyState === WebSocket.OPEN) {
    socket.send(JSON.stringify(message));
  }
}

export function closeWebSocket() {
  if (socket) {
    socket.close();
    socket = null;
  }
} 